import { PageContainer, ProCard } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Avatar, Col, Divider, Flex, Row, Space, Statistic, Tabs, Typography } from 'antd';
import { useEffect, useState } from 'react';

// 引入图表组件
import { Area, Bar, Column, Gauge, Line, Pie, Radar } from '@ant-design/charts';

// 引入API和类型
import {
  getClassTrippingRanking,
  getLowStockMaterials,
  getMaterialCategoryRatio,
  getMaterialInventoryTrend,
  getMaterialOverview,
  getMaterialUsageRanking,
  getSystemOverview,
  getTrippingPowerDistribution,
  getTrippingStats,
  getTrippingTimeDistribution,
  getUserActivity,
  getUserLoginStats,
  getUserOperationDistribution,
} from '@/services/dashboardApi';
import {
  ApiResponse,
  ClassTrippingRanking,
  LowStockMaterial,
  MaterialCategoryRatio,
  MaterialInventoryTrend,
  MaterialOverview,
  MaterialUsageRanking,
  SystemOverview,
  TrippingPowerDistribution,
  TrippingStats,
  TrippingTimeDistribution,
  UserActivity,
  UserLoginStats,
  UserOperationDistribution,
} from './types';

// 引入组件
import DashboardHeader from './components/Header';
import LowStockMaterialList from './components/LowStockMaterialList';
import TrippingRecordList from './components/TrippingRecordList';

// 定义周期选项
const periodOptions = [
  { label: '近一周', value: 'week' },
  { label: '近一月', value: 'month' },
  { label: '近三月', value: 'quarter' },
  { label: '近一年', value: 'year' },
];

export default function Dashboard() {
  // 状态管理
  const [activePeriod, setActivePeriod] = useState<string>('month');
  
  // 获取系统概览数据
  const { data: systemOverview, loading: systemLoading } = useRequest<ApiResponse<SystemOverview>>(
    getSystemOverview,
    {
      onError: (error) => {
        console.error('获取系统概览数据失败:', error);
      },
    },
  );

  // 获取物资库存概况
  const { data: materialOverview, loading: materialOverviewLoading } = useRequest<ApiResponse<MaterialOverview>>(
    getMaterialOverview,
    {
      onError: (error) => {
        console.error('获取物资库存概况失败:', error);
      },
    },
  );

  // 获取用户活跃度数据
  const { data: userActivity, loading: userActivityLoading } = useRequest<ApiResponse<UserActivity>>(
    () => getUserActivity(),
    {
      onError: (error) => {
        console.error('获取用户活跃度数据失败:', error);
      },
    },
  );

  // 获取物资分类占比
  const { data: categoryRatio, loading: categoryRatioLoading } = useRequest<ApiResponse<MaterialCategoryRatio[]>>(
    getMaterialCategoryRatio,
    {
      onError: (error) => {
        console.error('获取物资分类占比失败:', error);
      },
    },
  );

  // 获取物资库存趋势
  const { data: inventoryTrend, loading: inventoryTrendLoading, run: fetchInventoryTrend } = 
    useRequest<ApiResponse<MaterialInventoryTrend>>(
      (params) => getMaterialInventoryTrend(params),
      {
        manual: true,
        onError: (error) => {
          console.error('获取物资库存趋势失败:', error);
        },
      },
    );

  // 获取物资使用频率排行
  const { data: usageRanking, loading: usageRankingLoading, run: fetchUsageRanking } = 
    useRequest<ApiResponse<MaterialUsageRanking[]>>(
      (params) => getMaterialUsageRanking(10, params),
      {
        manual: true,
        onError: (error) => {
          console.error('获取物资使用频率排行失败:', error);
        },
      },
    );

  // 获取库存预警物资
  const { data: lowStockMaterials, loading: lowStockLoading } = useRequest<ApiResponse<LowStockMaterial[]>>(
    () => getLowStockMaterials(10),
    {
      onError: (error) => {
        console.error('获取库存预警物资失败:', error);
      },
    },
  );

  // 获取跳闸记录统计
  const { data: trippingStats, loading: trippingStatsLoading, run: fetchTrippingStats } = 
    useRequest<ApiResponse<TrippingStats>>(
      (params) => getTrippingStats(params),
      {
        manual: true,
        onError: (error) => {
          console.error('获取跳闸记录统计失败:', error);
        },
      },
    );

  // 获取跳闸功率分布
  const { data: powerDistribution, loading: powerDistributionLoading } = 
    useRequest<ApiResponse<TrippingPowerDistribution[]>>(
      getTrippingPowerDistribution,
      {
        onError: (error) => {
          console.error('获取跳闸功率分布失败:', error);
        },
      },
    );

  // 获取跳闸时间分布
  const { data: timeDistribution, loading: timeDistributionLoading, run: fetchTimeDistribution } = 
    useRequest<ApiResponse<TrippingTimeDistribution>>(
      (type, period) => getTrippingTimeDistribution(type, period),
      {
        manual: true,
        onError: (error) => {
          console.error('获取跳闸时间分布失败:', error);
        },
      },
    );

  // 获取班级跳闸排行
  const { data: classRanking, loading: classRankingLoading, run: fetchClassRanking } = 
    useRequest<ApiResponse<ClassTrippingRanking[]>>(
      (params) => getClassTrippingRanking(10, params),
      {
        manual: true,
        onError: (error) => {
          console.error('获取班级跳闸排行失败:', error);
        },
      },
    );

  // 获取用户登录统计
  const { data: loginStats, loading: loginStatsLoading, run: fetchLoginStats } = 
    useRequest<ApiResponse<UserLoginStats>>(
      (params) => getUserLoginStats(params),
      {
        manual: true,
        onError: (error) => {
          console.error('获取用户登录统计失败:', error);
        },
      },
    );

  // 获取用户操作分布
  const { data: operationDistribution, loading: operationDistributionLoading, run: fetchOperationDistribution } = 
    useRequest<ApiResponse<UserOperationDistribution[]>>(
      (params) => getUserOperationDistribution(params),
      {
        manual: true,
        onError: (error) => {
          console.error('获取用户操作分布失败:', error);
        },
      },
    );

  // 将activePeriod映射到API所需的period格式
  const mapPeriodToApiFormat = (period: string) => {
    switch (period) {
      case 'week':
        return 'daily';
      case 'month':
        return 'daily';
      case 'quarter':
        return 'weekly';
      case 'year':
        return 'monthly';
      default:
        return 'daily';
    }
  };

  // 周期变化时重新获取数据
  useEffect(() => {
    // 根据选择的周期确定days参数
    let days = 30;
    if (activePeriod === 'week') days = 7;
    if (activePeriod === 'quarter') days = 90;
    if (activePeriod === 'year') days = 365;

    fetchInventoryTrend(mapPeriodToApiFormat(activePeriod), days);
    fetchUsageRanking(activePeriod);
    fetchTrippingStats(activePeriod);
    fetchTimeDistribution('hourly', activePeriod);
    fetchClassRanking(activePeriod);
    fetchLoginStats(activePeriod);
    fetchOperationDistribution(activePeriod);
  }, [activePeriod]);

  // 物资分类占比图表配置
  const categoryPieConfig = {
    data: categoryRatio?.data || [],
    angleField: 'count',
    colorField: 'categoryName',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [{ type: 'element-active' }],
  };

  // 物资库存趋势图表配置
  const inventoryTrendConfig = {
    data: inventoryTrend?.data?.trendData ? 
      inventoryTrend.data.trendData.map(item => ({
        date: item.timePoint,
        value: item.totalStock,
        inbound: item.inboundQuantity,
        outbound: item.outboundQuantity,
        netChange: item.netChange,
      })) : [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    areaStyle: () => ({ fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff' }),
    tooltip: {
      customContent: (title, items) => {
        const item = items[0];
        const data = item?.data as any;
        return data ? `
          <div style="padding: 8px;">
            <div style="margin-bottom: 4px;">${title}</div>
            <div>库存总量: ${data.value}</div>
            <div>入库数量: ${data.inbound}</div>
            <div>出库数量: ${data.outbound}</div>
            <div>净变化: ${data.netChange > 0 ? '+' : ''}${data.netChange}</div>
          </div>
        ` : '';
      }
    }
  };

  // 物资使用频率排行图表配置
  const usageRankingConfig = {
    data: usageRanking?.data || [],
    xField: 'usageCount',
    yField: 'materialName',
    seriesField: 'categoryName',
    legend: { position: 'top-right' },
  };

  // 跳闸功率分布图表配置
  const powerDistributionConfig = {
    data: powerDistribution?.data || [],
    xField: 'range',
    yField: 'count',
    label: {
      position: 'middle',
      style: { fill: '#FFFFFF', opacity: 0.6 },
    },
    meta: {
      range: { alias: '功率范围' },
      count: { alias: '跳闸次数' },
    },
  };

  // 跳闸时间分布图表配置
  const timeDistributionConfig = {
    data: timeDistribution?.data?.distribution || [],
    xField: 'timePoint',
    yField: 'count',
    meta: {
      timePoint: { alias: '时间点' },
      count: { alias: '跳闸次数' },
    },
  };

  // 班级跳闸排行图表配置
  const classRankingConfig = {
    data: classRanking?.data || [],
    xField: 'count',
    yField: 'className',
    meta: {
      className: { alias: '班级' },
      count: { alias: '跳闸次数' },
    },
    label: {
      position: 'right',
    },
  };

  // 用户登录统计图表配置
  const loginStatsConfig = {
    data: loginStats?.data?.timeDistribution || [],
    xField: 'date',
    yField: 'count',
    meta: {
      date: { alias: '日期' },
      count: { alias: '登录次数' },
    },
  };

  // 用户操作分布图表配置
  const operationDistributionConfig = {
    data: operationDistribution?.data || [],
    angleField: 'count',
    colorField: 'operation',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}%',
    },
  };

  // 用户角色分布雷达图配置
  const userRoleRadarConfig = {
    data: userActivity?.data?.userRoleDistribution.map(item => ({
      role: item.role,
      count: item.count,
    })) || [],
    xField: 'role',
    yField: 'count',
    meta: {
      role: {
        alias: '用户角色',
      },
      count: {
        alias: '用户数量',
      },
    },
    area: {},
  };

  return (
    <PageContainer
      header={{
        title: '数据大屏',
      }}
    >
      {/* 头部统计信息 */}
      <ProCard gutter={[16, 16]} ghost>
        <ProCard colSpan={24}>
          <DashboardHeader 
            systemOverview={systemOverview?.data} 
            userActivity={userActivity?.data}
            loading={systemLoading || userActivityLoading}
          />
        </ProCard>
      </ProCard>

      {/* 周期选择器 */}
      <ProCard style={{ marginTop: 16 }}>
        <Tabs
          activeKey={activePeriod}
          onChange={setActivePeriod}
          tabBarStyle={{ display: 'flex', justifyContent: 'center' }}
          items={periodOptions.map(option => ({
            key: option.value,
            label: option.label,
            style: { minWidth: '100px', textAlign: 'center' }
          }))}
        />
      </ProCard>

      {/* 物资概览 */}
      <ProCard title="物资概览" style={{ marginTop: 16 }} gutter={[16, 16]} ghost>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} layout="center" bordered loading={materialOverviewLoading} style={{ height: 320 }}>
          <Flex vertical align="center" justify="center" style={{ height: '100%' }}>
            <Statistic 
              title="物资总数" 
              value={systemOverview?.data?.materialCount || 0}
              style={{ textAlign: 'center' }}
            />
            <Flex justify="space-around" align="center" style={{ marginTop: 24, width: '100%', flexWrap: 'nowrap' }}>
              <div style={{ textAlign: 'center', padding: '0 8px', flex: 1 }}>
                <Statistic 
                  title="正常库存" 
                  value={materialOverview?.data?.normal || 0}
                  style={{ textAlign: 'center'}}
                />
              </div>
              <Divider type="vertical" style={{ height: '50px' }} />
              <div style={{ textAlign: 'center', padding: '0 8px', flex: 1}}>
                <Statistic 
                  title="库存不足" 
                  value={materialOverview?.data?.lowStock || 0} 
                  valueStyle={{ color: '#cf1322' }}
                  style={{ textAlign: 'center' }}
                />
              </div>
              <Divider type="vertical" style={{ height: '50px' }} />
              <div style={{ textAlign: 'center', padding: '0 8px', flex: 1 }}>
                <Statistic 
                  title="已报废" 
                  value={materialOverview?.data?.scrapped || 0}
                  style={{ textAlign: 'center' }}
                />
              </div>
            </Flex>
          </Flex>
        </ProCard>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} bordered loading={categoryRatioLoading} style={{ height: 320 }}>
          <Typography.Title level={5}>物资分类占比</Typography.Title>
          <Pie height={240} {...categoryPieConfig} />
        </ProCard>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} bordered loading={lowStockLoading} style={{ height: 320, overflow: 'auto' }}>
          <LowStockMaterialList data={lowStockMaterials?.data || []} />
        </ProCard>
      </ProCard>

      {/* 物资趋势 */}
      <ProCard title="物资趋势" style={{ marginTop: 16 }} gutter={[16, 16]} ghost>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 12 }} bordered loading={inventoryTrendLoading}>
          <Typography.Title level={5}>物资库存趋势</Typography.Title>
          <Area height={300} {...inventoryTrendConfig} />
        </ProCard>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 12 }} bordered loading={usageRankingLoading}>
          <Typography.Title level={5}>物资使用频率排行</Typography.Title>
          <Bar height={300} {...usageRankingConfig} />
        </ProCard>
      </ProCard>

      {/* 跳闸记录 */}
      <ProCard title="跳闸记录" style={{ marginTop: 16 }} gutter={[16, 16]} ghost>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} bordered loading={trippingStatsLoading}>
          <Statistic title="跳闸总数" value={trippingStats?.data?.totalCount || 0} />
          <Flex justify="space-around" style={{ marginTop: 24 }}>
            <Statistic title="已处理" value={trippingStats?.data?.handledCount || 0} valueStyle={{ color: '#3f8600' }} />
            <Statistic title="未处理" value={trippingStats?.data?.pendingCount || 0} valueStyle={{ color: '#cf1322' }} />
          </Flex>
          <Divider />
          <Flex justify="space-around">
            <Statistic title="平均功率" value={trippingStats?.data?.averagePower || 0} suffix="kW" />
            <Statistic title="最大功率" value={trippingStats?.data?.maxPower || 0} suffix="kW" />
          </Flex>
        </ProCard>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} bordered loading={powerDistributionLoading}>
          <Typography.Title level={5}>跳闸功率分布</Typography.Title>
          <Column height={200} {...powerDistributionConfig} />
        </ProCard>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} bordered loading={timeDistributionLoading}>
          <Typography.Title level={5}>跳闸时间分布</Typography.Title>
          <Line height={200} {...timeDistributionConfig} />
        </ProCard>
      </ProCard>

      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        <Col xs={24} sm={24} md={12}>
          <ProCard title="班级跳闸排行" bordered loading={classRankingLoading}>
            <Bar height={300} {...classRankingConfig} />
          </ProCard>
        </Col>
        <Col xs={24} sm={24} md={12}>
          <ProCard title="待处理跳闸记录" bordered>
            <TrippingRecordList />
          </ProCard>
        </Col>
      </Row>

      {/* 用户行为 */}
      <ProCard title="用户行为" style={{ marginTop: 16 }} gutter={[16, 16]} ghost>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} bordered loading={userActivityLoading}>
          <Typography.Title level={5}>用户角色分布</Typography.Title>
          <Radar height={300} {...userRoleRadarConfig} />
        </ProCard>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} bordered loading={loginStatsLoading}>
          <Typography.Title level={5}>用户登录统计</Typography.Title>
          <Line height={300} {...loginStatsConfig} />
        </ProCard>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 8 }} bordered loading={operationDistributionLoading}>
          <Typography.Title level={5}>用户操作分布</Typography.Title>
          <Pie height={300} {...operationDistributionConfig} />
        </ProCard>
      </ProCard>
    </PageContainer>
  );
}